import router from '@/router'
import { accountLoginRequest, getUserInfoByid, getUserMenusByRoleId } from '@/service/login/login'
import { localCache } from '@/utils/cache'
import { id, th } from 'element-plus/es/locales.mjs'
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'

interface ILoginState {
  token: string
  userInfo: any
  userMenus: any
}
const userLoginStore = defineStore('login', {
  state: (): ILoginState => ({
    token: localCache.getCache('token') ?? '',
    userInfo: localCache.getCache('userInfo') ?? {},
    userMenus: localCache.getCache('userMenus') ?? [],
  }),
  actions: {
    async loginAccountAction(account: { name: string; password: string }) {
      const loginResult = await accountLoginRequest(account)
      const id = loginResult.data.id
      this.token = loginResult.data.token
      const name = loginResult.data.name
      localCache.setCache('token', this.token)

      // 获取用户信息
      const userInfoResult = await getUserInfoByid(id)
      this.userInfo = userInfoResult.data

      // 根据角色来获取对应的菜单
      const userMenusResult = await getUserMenusByRoleId(this.userInfo.role.id)
      this.userMenus = userMenusResult.data

      // 进行本地缓存
      localCache.setCache('userInfo', this.userInfo)
      localCache.setCache('userMenus', this.userMenus)

      // 动态的添加路由
      const localRoutes: RouteRecordRaw[] = []
      // 读取router/main所有的ts文件
      const filses: Record<string, any> = import.meta.glob('../../router/main/**/*.ts', {
        eager: true,
      })

      for (const key in filses) {
        const module = filses[key]
        console.log(module.default)
        localRoutes.push(module.default)
      }
      for (const menu of this.userMenus) {
        for (const submenu of menu.children) {
          const route = localRoutes.find((item) => item.path === submenu.url)
          if (route) {
            router.addRoute('main', route)
          }
        }
      }

      // 页面跳转(main页面)
      router.push('/main')
    },
  },
})

export default userLoginStore
